# -*- coding: utf-8 -*-

import pygeoip

from json import dumps

from django.http import HttpResponse
from django.http import HttpResponseRedirect

from django.contrib.auth import authenticate 
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required 

from django.template import RequestContext
from django.template.loader import get_template

from forms import *
from people.models import People

from handle import _handle_register
from handle import _handle_validate

from codename_bamboo.preference import JSON_MIME
from codename_bamboo.preference import GEOIP_CITY_DATABASE
geoip = pygeoip.GeoIP(GEOIP_CITY_DATABASE)       


def validate(request):
    """
    Serve ajax validate request, 
    while people are registering
    """
    if not request.is_ajax():
        return HttpResponseRedirect('/')
    else:
        if request.method == 'POST':
            results  = dumps({'ok': False})
            response = HttpResponse(results, mimetype=JSON_MIME)

            return response
        else:
            if not 'username' in request.GET:
                results  = dumps({'ok': False})
                response = HttpResponse(results, mimetype=JSON_MIME)

                return response
            else:
                exists = _handle_validate(request)
                if exists:
                    results  = dumps({'ok': True, 'exists': True})
                    response = HttpResponse(results, mimetype=JSON_MIME)

                    return response
                else:
                    results  = dumps({'ok': True, 'exists': False})
                    response = HttpResponse(results, mimetype=JSON_MIME)

                    return response


def register(request):
    """
    Serve people's reigster request
    """
    if request.method == 'GET':
        signin_form = SignInForm()
        register_form = RegisterForm()
        template = get_template('account/register.dtpl')
        context = RequestContext(request, {'register_form':register_form
                                          ,'signin_form':signin_form
                                           })
        response = HttpResponse(template.render(context))

        if not 'homeLatitude' in request.session or not 'homeLongitude' in request.session:
            record    = geoip.record_by_addr('114.82.3.100') # request.META['REMOTE_ADDR'])
            latitude  = str(record['latitude'])
            longitude = str(record['longitude'])

        else:
            latitude = request.session['homeLatitude']
            longitude = request.session['homeLongitude']

        response.set_cookie('homeLatitude', latitude)
        response.set_cookie('homeLongitude', longitude)

        return response
    else:  # POST
        success = _handle_register(request)
        if success:
            return HttpResponseRedirect('/home/')
        else:
            return HttpResponseRedirect('/')


def signin(request):
    """
    Serve people's signin request
    """
    if request.method == 'GET':
        return HttpResponseRedirect('/')
    else:
        username = request.POST['signin_username']
        password = request.POST['signin_password']
        print(username)
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/home/')
        else:
            return HttpResponseRedirect('/')


def confirm(request):
    """
    Confirm people's location
    """
    pass


@login_required
def signout(request):
    """
    Serve people's signout request
    """
    logout(request)
    return HttpResponseRedirect('/')
